package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.api.shopapi.entity.BusinessStaffRel;
import com.api.shopapi.entity.MyResult;
import com.api.shopapi.entity.PreCheck;
import com.api.shopapi.service.BusinessStaffRelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;

/**
 * 商家的后台账号
 * */

@RestController
@RequestMapping("BusinessStaffRel")
public class BusinessStaffRelController extends BaseController {

    @Autowired
    @Qualifier("BusinessStaffRelServiceImplOne")
    private BusinessStaffRelService businessStaffRelService;



    //编辑
    @RequestMapping(value = "Edit",method = RequestMethod.POST)
    public MyResult Edit(@RequestBody JSONObject jsonObject) {

        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String businessCode = jsonObject.getString("businessCode");
            JSONArray listStaff = jsonObject.getJSONArray("listStaff");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/BusinessStaffRel/Edit");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            //删除老的关系
            List<BusinessStaffRel> listBusinessStaffRel = businessStaffRelService.getListByBusinessCode(businessCode);
            for(BusinessStaffRel businessStaffRel : listBusinessStaffRel){
                businessStaffRelService.deleteByBusinessStaffRelCode(businessStaffRel.getBusinessStaffRelCode());
            }

            //增加新的关系
            for (int k = 0; k < listStaff.size(); k++) {

                JSONObject staffTemp = listStaff.getJSONObject(k);

                BusinessStaffRel businessStaffRel = new BusinessStaffRel();
                businessStaffRel.setBusinessStaffRelCode(UUID.randomUUID().toString());
                businessStaffRel.setBusinessCode(businessCode);
                businessStaffRel.setStaffCode(staffTemp.getString("staffCode"));
                businessStaffRelService.insert(businessStaffRel);
            }



            Object data = new Object[] { };
            return success(data);

        }catch (Exception e){
            insertError("/BusinessStaffRel/Edit",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }


}
